<template>
  <div class="app-container">
    <el-card class="box-card">
      <el-row>
        <el-col :span="3">
          <el-button
            type="primary"
            icon="el-icon-plus"
            size="mini"
            @click="handleAdd"
            >新增项</el-button
          >
        </el-col>
        <el-col :span="3">
          <el-button
            type="danger"
            icon="el-icon-plus"
            size="mini"
            @click="handleInit"
            >初始化</el-button
          >
        </el-col>
      </el-row>
      <el-table
        :data="dataList"
        border
        v-loading="listLoading"
        fit
        size="small"
        highlight-current-row
        style="width: 100%"
      >
        <el-table-column
          type="index"
          label="#"
          align="center"
        ></el-table-column>
        <el-table-column
          v-for="item in tableColumns"
          :label="item.title"
          :key="item.key"
          :align="item.align ? item.align : 'center'"
          :width="item.width ? item.width : ''"
          :prop="item.key"
          :formatter="dataFormatter"
        ></el-table-column>

        <el-table-column align="center" label="操作" width="300px">
          <template slot-scope="scope">
            <el-button
              type="primary"
              size="mini"
              icon="el-icon-edit"
              @click="handleEdit(scope)"
              >编辑</el-button
            >
            <el-button
              type="danger"
              size="mini"
              icon="el-icon-delete"
              @click="handleDelete(scope)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <!-- 对话框表单 -->
    <el-dialog
      :visible.sync="dialogVisible"
      :title="dialogType === 'edit' ? '编辑初始账户' : '新增初始账户'"
      width="50%"
    >
      <el-form
        :model="form"
        :rules="formRules"
        ref="formRef"
        label-width="80px"
        label-position="right"
        style="width: 95%; padding: 0 30px"
      >
        <el-form-item label="账户名称" prop="name">
          <el-input
            type="text"
            v-model="form.name"
            placeholder="账户名称"
            clearable
          />
        </el-form-item>
        <el-form-item label="金额" prop="money">
          <el-input v-model="form.money" placeholder="输入金额" clearable>
            <template slot="append">元</template>
          </el-input>
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button type="danger" size="small" @click="dialogVisible = false"
          >取消</el-button
        >
        <el-button type="primary" size="small" @click="handleSave"
          >保存</el-button
        >
      </div>
    </el-dialog>
    <!-- 初始化 -->
    <el-dialog
      :visible.sync="dlgInitVisible"
      title="财务初始化列表"
      width="40%"
    >
      <el-form
        :model="initForm"
        ref="initFormRef"
        label-width="10px"
        label-position="right"
        style="width: 95%; padding: 0 30px"
      >
        <el-form-item>
          <el-row>
            <el-col :span="24">
              <el-checkbox v-model="initForm.acc_title">会计科目</el-checkbox>
            </el-col>
            <el-col :span="24">
              <el-checkbox v-model="initForm.employee">员工信息</el-checkbox>
            </el-col>
            <el-col :span="24">
              <el-checkbox v-model="initForm.customer">客户信息</el-checkbox>
            </el-col>
            <!-- <el-col :span="24">
              <el-checkbox v-model="initForm.bank">银行信息</el-checkbox>
            </el-col> -->
            <el-col :span="24">
              <el-checkbox v-model="initForm.rule">利润分配规则</el-checkbox>
            </el-col>
            <el-col :span="24">
              <el-checkbox v-model="initForm.sale">销售单</el-checkbox>
            </el-col>
            <el-col :span="24">
              <el-checkbox v-model="initForm.receipt">律师费收款单</el-checkbox>
            </el-col>
            <el-col :span="24">
              <el-checkbox v-model="initForm.pay">律师费付款单</el-checkbox>
            </el-col>
            <el-col :span="24">
              <el-checkbox v-model="initForm.expense">费用单</el-checkbox>
            </el-col>
            <el-col :span="24">
              <el-checkbox v-model="initForm.income">其他收入</el-checkbox>
            </el-col>
            <el-col :span="24">
              <el-checkbox v-model="initForm.borrow">资金借入</el-checkbox>
            </el-col>
            <el-col :span="24">
              <el-checkbox v-model="initForm.lend">资金借出</el-checkbox>
            </el-col>
            <el-col :span="24">
              <el-checkbox v-model="initForm.journal">流水账</el-checkbox>
            </el-col>
          </el-row>
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button type="danger" size="small" @click="dlgInitVisible = false"
          >取消</el-button
        >
        <el-button type="primary" size="small" @click="handleInitData"
          >初始化</el-button
        >
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  getInitAccount,
  addInitAccount,
  updateInitAccount,
  delInitAccount,
  initData,
} from "@/api/bank";

const defaultForm = {
  id: null,
  name: "",
  money: 0,
};

export default {
  name: "Init",
  data() {
    const checkMoney = (rule, value, callback) => {
      if (value.length === 0) {
        return callback(new Error("金额不能为空"));
      }
      if (isNaN(value)) {
        callback(new Error("请输入数字值"));
      } else {
        if (value <= 0) {
          callback(new Error("必须大于零"));
        } else {
          callback();
        }
      }
    };

    return {
      form: Object.assign({}, defaultForm),
      formRules: {
        name: [{ required: true, message: "请输入名称", trigger: "blur" }],
        money: [{ validator: checkMoney, trigger: "blur" }],
      },
      initForm: {
        acc_title: true,
        employee: true,
        customer: true,
        bank: true,
        rule: true,
        sale: true,
        receipt: true,
        expense: true,
        income: true,
        borrow: true,
        lend: true,
        pay: true,
        journal: true,
      },
      dialogVisible: false,
      dlgInitVisible: false,
      dialogType: "new",
      dataList: [],
      listLoading: true,
      tableColumns: [
        {
          key: "name",
          title: "账号名称",
        },
        {
          key: "money",
          title: "金额(元)",
        },
      ],
    };
  },
  created() {
    this.getInitData();
  },
  methods: {
    // 列表
    getInitData() {
      this.listLoading = true;
      getInitAccount()
        .then((res) => {
          this.dataList = res;
          this.listLoading = false;
        })
        .catch((error) => {
          console.log(error.message);
          this.$message.error("获取数据失败");
          this.listLoading = false;
        });
    },
    handleInit() {
      this.dlgInitVisible = true;
    },
    handleInitData() {
      this.$confirm(
        "初始化会清空下列选中模块的数据，真的要初始化吗?",
        "初始化提示：",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      )
        .then(async () => {
          try {
            const res = await initData(this.initForm);
            if (res.status_code == "success") {
              this.$message.success(res.message);
            } else {
              this.$message.success(res.message);
            }
          } catch (error) {
            this.$message.error("初始化失败!");
          }
        })
        .catch((err) => {
          console.error(err);
          this.$message.info("已经取消初始化!");
        });
    },
    // 增加
    handleAdd() {
      this.form = Object.assign({}, defaultForm);

      this.dialogType = "new";
      this.dialogVisible = true;

      this.$nextTick(() => {
        this.$refs.formRef.clearValidate();
      });
    },
    dataFormatter(row, column, cellValue, index) {
      if (column.property == "money") {
        return row.money.toFixed(2);
      } else {
        return cellValue;
      }
    },
    // 修改
    handleEdit(scope) {
      this.form = Object.assign({}, scope.row);
      this.dialogType = "edit";

      this.dialogVisible = true;
      this.$nextTick(() => {
        this.$refs.formRef.clearValidate();
      });
    },
    // 删除
    handleDelete({ $index, row }) {
      this.$confirm("确定要删除该账户吗?", "删除提示：", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          const res = await delInitAccount(row.id);

          this.dataList.splice($index, 1);
          this.$message({
            type: "success",
            message: "删除成功!",
          });
        })
        .catch((err) => {
          console.error(err);
          this.$message.error("取消删除!");
        });
    },
    // 保存操作
    async handleSave() {
      this.$refs.formRef.validate(async (valid) => {
        if (!valid) return;

        const isEdit = this.dialogType === "edit";
        if (isEdit) {
          const res = await updateInitAccount(this.form);
          console.log(isEdit, res);
          const index = this.dataList.findIndex((v) => v.id === res.id);
          this.dataList.splice(index, 1, res);
        } else {
          const res = await addInitAccount(this.form);
          const { id } = res;
          if (id > 0) {
            this.getInitData();
          }
        }

        const { name } = this.form;

        this.dialogVisible = false;
        this.$notify({
          title: "Success",
          dangerouslyUseHTMLString: true,
          message: `
              <div>银行账户: ${name}</div>
            `,
          type: "success",
        });
      });
    },
  },
};
</script>

<style lang='scss' scoped>
// .el-form-item {
//   margin-bottom: 0;
// }
</style>